import 'dart:async';
import 'dart:math';

import 'package:common_utils/common_utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:news/com.comm/model/notify.dart';
import 'package:news/com.comm/widget/net_loading_dialog.dart';
import 'package:oktoast/oktoast.dart';

Color hexToColor(String s) {
  // 如果传入的十六进制颜色值不符合要求，返回默认值
  if (s.length != 7 || int.tryParse(s.substring(1, 7), radix: 16) == null) {
    s = '#999999';
  }

  return new Color(int.parse(s.substring(1, 7), radix: 16) + 0xFF000000);
}

///获取时间年月日
String getTimeYMD(String time) {
  String newTime = "";
  if (time.isEmpty) {
    return newTime;
  }
  if (!time.contains(" ")) {
    return time;
  } else {
    newTime = time.split(" ")[0];
  }
  if (!TextUtil.isEmpty(newTime)) {
    newTime = newTime.replaceAll("-", ".");
  }
  return newTime;
}

/* 处理时间.0 */
String rDate(date) {
  if (date == null) {
    return '-';
  }
  return date.replaceAll(new RegExp(r'.\d+$'), '');
}

/* 字数限制 */
String subStr(str, {int limitLength = 10}) {
  try {
    dynamic newRunes = str.runes.toList();
    if (newRunes.length > limitLength) {
      return String.fromCharCodes(newRunes.sublist(0, limitLength)) + '...';
    } else {
      return str;
    }
  } on Exception catch (e) {
    debugPrint(e.toString());
    return str;
  }
}

/* 将时间转换为 00~09 */
String formatTime(int timeNum) {
  return timeNum < 10 ? "0" + timeNum.toString() : timeNum.toString();
}

/* 时间格式化，根据总秒数转换为对应的 hh:mm:ss 格式 */
String constructTime(int seconds) {
  // int hour = seconds ~/ 3600;
  int minute = seconds % 3600 ~/ 60;
  int second = seconds % 60;
  return formatTime(minute) + ":" + formatTime(second);
}

bool stringIsNotEmpty(var string) {
  if (string != null &&
      string.toString().isNotEmpty &&
      string.toString() != "null") {
    return true;
  } else {
    return false;
  }
}

Future<void> showLoadingDialog(BuildContext context, Function function,
    {String? loadingText}) {
  showDialog(
    context: context,
    barrierDismissible: false,
    builder: (_) {
      return GestureDetector(child:NetLoadingDialog(
        dismissDialog: function,
        loadingText: loadingText ?? '加载中...',
        outsideDismiss: false,
      ),onLongPress: (){
        Navigator.of(context).pop();
      },);
    },
  );
  return Future.value();
}

//弹出确认提示弹窗
void showTipsDialog(BuildContext context, String title, String msg) {
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return CupertinoAlertDialog(
        title: Text(
          msg,
          style: TextStyle(
            fontSize: 14,
            color: hexToColor('#333333'),
          ),
        ),
        content: Container(
            margin: EdgeInsets.only(top: 20, left: 10.0, right: 10.0),
            child: Text(
              "请联系电话客服 4008233088",
              style: TextStyle(fontSize: 14, color: hexToColor('#999999')),
            )),
        actions: <Widget>[
          CupertinoButton(
            child: Text("确定"),
            onPressed: () {
              Navigator.pop(context);
            },
          ),
        ],
      );
    },
  );
}

void showCustomDoubleDialog(
    BuildContext context, String title, String content, Function fun) {
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return CupertinoAlertDialog(
        title: Text(
          title,
          style: TextStyle(fontSize: 14),
        ),
        content: Text(
          content,
          style: TextStyle(fontSize: 14),
        ),
        actions: <Widget>[
          CupertinoButton(
            child: Text("确认"),
            onPressed: () {
              fun();
            },
          ),
        ],
      );
    },
  );
}

void showTipsAlertDialog(
    BuildContext context, String title, String content, Function fun) {
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        title: Text(
          title,
          style: TextStyle(fontSize: 14),
        ),
        content: Text(
          content,
          style: TextStyle(fontSize: 14),
        ),
        actions: <Widget>[
          TextButton(
            onPressed: () {
              Navigator.pop(context);
            },
            child: const Text('确定'),
          ),
        ],
      );
    },
  );
}

void showSimpleDialog(
    BuildContext context, String title, String content, Function fun) {
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return SimpleDialog(
        title: Text(
          title,
          style: TextStyle(fontSize: 14),
        ),
        children: <Widget>[
          TextButton(
            onPressed: () {
              Navigator.pop(context);
            },
            child: const Text('确定'),
          )
        ],
      );
    },
  );
}

/**
 * 写入翻译前确认弹窗
 */
void showWriteTranslateSureKeyDialog(
  BuildContext context,
  String title,
  String key,
  bool isEdit,
  String okText,
  Function fun,
) {
  final TextEditingController _controller_key = TextEditingController();
  _controller_key.text = key;
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        title: Text(
          title,
          style: TextStyle(fontSize: 14),
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            SizedBox(
              height: 16,
            ),
            SizedBox(
              width: 600,
              child: SizedBox(
                  width: 380,
                  child: TextField(
                    enabled: isEdit,
                    controller: _controller_key,
                    decoration: InputDecoration(
                      hintText: '请确认多语言翻译key',
                      border: OutlineInputBorder(),
                    ),
                  )),
            ),
          ],
        ),
        actions: <Widget>[
          TextButton(
            child: Text(okText),
            onPressed: () {
              String key = _controller_key.text.trim();
              if (key.isEmpty) {
                showToast("多语言key不能为空");
                return;
              }
              Navigator.pop(context);
              fun(key);
            },
          ),
          TextButton(
            child: Text("取消"),
            onPressed: () {
              Navigator.pop(context);
            },
          ),
        ],
      );
    },
  );
}

/**
 * 新增多语言写入路径弹窗
 */
void showAddResPathDialog(BuildContext context, String title, Function fun) {
  final TextEditingController _controller_key = TextEditingController();
  final TextEditingController _controller_value = TextEditingController();
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
        title: Text(
          title,
          style: TextStyle(fontSize: 14),
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            SizedBox(
              height: 16,
            ),
            SizedBox(
                width: 600,
                child: Row(children: [
                  SizedBox(
                      width: 200,
                      child: TextField(
                        controller: _controller_key,
                        decoration: InputDecoration(
                          labelText: '请输入简称',
                          hintText: '请输入简称',
                          border: OutlineInputBorder(),
                        ),
                      )),
                  SizedBox(
                    width: 16,
                  ),
                  SizedBox(
                      width: 380,
                      child: TextField(
                        controller: _controller_value,
                        decoration: InputDecoration(
                          labelText: '请输入翻译路径',
                          hintText: '请输入翻译路径',
                          border: OutlineInputBorder(),
                        ),
                      )),
                ])),
          ],
        ),
        actions: <Widget>[
          TextButton(
            child: Text("确认"),
            onPressed: () {
              String key = _controller_key.text.trim();
              String value = _controller_value.text.trim();
              if (key.isEmpty) {
                showToast("简称不能为空");
                return;
              }
              if (value.isEmpty) {
                showToast("路径不能为空");
                return;
              }
              Navigator.pop(context);
              fun(key, value);
            },
          ),
          TextButton(
            child: Text("取消"),
            onPressed: () {
              Navigator.pop(context);
            },
          ),
        ],
      );
    },
  );
}

/**
 * 多语言路径选择弹窗
 */
void showResListSelectDialog(
    BuildContext context, String title, List<String> map, Function fun) {
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return SimpleDialog(
          title: Text(
            title,
            style: TextStyle(fontSize: 14),
          ),
          children: map.map((String choice) {
            return PopupMenuItem<String>(
              value: choice,
              onTap: () {
                debugPrint("select：${choice}");
                fun(choice);
              },
              child: Text(choice),
            );
          }).toList());
    },
  );
}

void showToast(String text) {
  final Widget widget = Center(
    child: ClipRRect(
      borderRadius: BorderRadius.circular(4.0),
      child: Container(
        width: 300.0,
        height: 120.0,
        color: Colors.grey.withOpacity(0.9),
        child: Center(
          child: Text(text, style: TextStyle(color: Colors.white)),
        ),
      ),
    ),
  );
  showToastWidget(
    widget,
    duration: const Duration(milliseconds: 1500),
    onDismiss: () {
      // The method will be called on toast dismiss.
      debugPrint('Toast has been dismissed.');
    },
  );
}

///计算与当前时间差值
String handleDate(String oldTime) {
  if (oldTime.isEmpty) {
    return "";
  }
  String nowTime =
      new DateTime.now().toString().split('.')[0].replaceAll('-', '/');
  int nowYear = int.parse(nowTime.split(" ")[0].split('/')[0]);
  int nowMonth = int.parse(nowTime.split(" ")[0].split('/')[1]);
  int nowDay = int.parse(nowTime.split(" ")[0].split('/')[2]);
  int nowHour = int.parse(nowTime.split(" ")[1].split(':')[0]);
  int nowMin = int.parse(nowTime.split(" ")[1].split(':')[1]);

  int oldYear = int.parse(oldTime.split(" ")[0].split('-')[0]);
  int oldMonth = int.parse(oldTime.split(" ")[0].split('-')[1]);
  int oldDay = int.parse(oldTime.split(" ")[0].split("-")[2]);
  int oldHour = int.parse(oldTime.split(" ")[1].split(':')[0]);
  int oldMin = int.parse(oldTime.split(" ")[1].split(':')[1]);

  var now = new DateTime(nowYear, nowMonth, nowDay, nowHour, nowMin);
  var old = new DateTime(oldYear, oldMonth, oldDay, oldHour, oldMin);
  var difference = now.difference(old);
  if (difference.inDays > 1) {
    if (difference.inHours - (difference.inDays * 24) - nowHour >= 24) {
      return (difference.inDays + 1).toString() + '天前';
    } else {
      return (difference.inDays).toString() + '天前';
    }
  } else if (difference.inDays == 1) {
    if (difference.inHours - nowHour >= 24) {
      return 2.toString() + '天前';
    } else {
      return '昨天'.toString();
    }
  } else if (difference.inHours >= 1 && difference.inHours < 24) {
    return (difference.inHours).toString() + '小时前';
  } else if (difference.inMinutes > 5 && difference.inMinutes < 60) {
    return (difference.inMinutes).toString() + '分钟前';
  } else if (difference.inMinutes <= 5) {
    return '刚刚';
  }
  return "";
}

///计算与当前时间差值 天时分秒
List<String> handleDateHMS(String oldTime) {
  List<String> listTime = [];
  if (oldTime.isEmpty) {
    listTime.add("0");
    listTime.add("0");
    listTime.add("0");
    listTime.add("0");
    return listTime;
  }
  String nowTime =
      new DateTime.now().toString().split('.')[0].replaceAll('-', '/');
  int nowYear = int.parse(nowTime.split(" ")[0].split('/')[0]);
  int nowMonth = int.parse(nowTime.split(" ")[0].split('/')[1]);
  int nowDay = int.parse(nowTime.split(" ")[0].split('/')[2]);
  int nowHour = int.parse(nowTime.split(" ")[1].split(':')[0]);
  int nowMin = int.parse(nowTime.split(" ")[1].split(':')[1]);

  int oldYear = int.parse(oldTime.split(" ")[0].split('-')[0]);
  int oldMonth = int.parse(oldTime.split(" ")[0].split('-')[1]);
  int oldDay = int.parse(oldTime.split(" ")[0].split("-")[2]);
  int oldHour = int.parse(oldTime.split(" ")[1].split(':')[0]);
  int oldMin = int.parse(oldTime.split(" ")[1].split(':')[1]);

  var now = new DateTime(nowYear, nowMonth, nowDay, nowHour, nowMin);
  var old = new DateTime(oldYear, oldMonth, oldDay, oldHour, oldMin);
  var difference = now.difference(old);
  int _day = (difference.inSeconds ~/ 3600) ~/ 24;
  int hour = (difference.inSeconds ~/ 3600) % 24;
  int minute = difference.inSeconds % 3600 ~/ 60;
  int second = difference.inSeconds % 60;
  String _day1 = _day.toString();
  String _hour1 = hour.toString();
  String _minute1 = minute.toString();
  String _second1 = second.toString();
  listTime.add(_day1);
  listTime.add(_hour1);
  listTime.add(_minute1);
  listTime.add(_second1);
  return listTime;
}

///计算与当前时间差值
bool checkDate(String oldTime) {
  if (oldTime.isEmpty) {
    return false;
  }
  String nowTime =
      new DateTime.now().toString().split('.')[0].replaceAll('-', '/');
  int nowYear = int.parse(nowTime.split(" ")[0].split('/')[0]);
  int nowMonth = int.parse(nowTime.split(" ")[0].split('/')[1]);
  int nowDay = int.parse(nowTime.split(" ")[0].split('/')[2]);
  int nowHour = int.parse(nowTime.split(" ")[1].split(':')[0]);
  int nowMin = int.parse(nowTime.split(" ")[1].split(':')[1]);

  int oldYear = int.parse(oldTime.split(" ")[0].split('-')[0]);
  int oldMonth = int.parse(oldTime.split(" ")[0].split('-')[1]);
  int oldDay = int.parse(oldTime.split(" ")[0].split("-")[2]);
  int oldHour = int.parse(oldTime.split(" ")[1].split(':')[0]);
  int oldMin = int.parse(oldTime.split(" ")[1].split(':')[1]);

  DateTime now = new DateTime(nowYear, nowMonth, nowDay, nowHour, nowMin);
  DateTime old = new DateTime(oldYear, oldMonth, oldDay, oldHour, oldMin);
  if (now.millisecondsSinceEpoch < old.millisecondsSinceEpoch) {
    return true;
  } else {
    return false;
  }
}

///随机数
String randomBit(int len) {
  String scopeF = '123456789'; //首位
  String scopeC = '0123456789'; //中间
  String result = '';
  for (int i = 0; i < len; i++) {
    if (i == 0) {
      result = scopeF[Random().nextInt(scopeF.length)];
    } else {
      result = result + scopeC[Random().nextInt(scopeC.length)];
    }
  }
  return result;
}

///判断是否是生产环境
bool isProductEnvironment() {
  // return  programType == fluwx.WXMiniProgramType.RELEASE;
  return true;
}

//判断商品是否可以正常购买
bool isGroundingProduct(int status) {
  bool isGrounding = true;
  if (status == 0) {
    isGrounding = true;
  } else {
    if (status == 1) {
      //0是正常的  1是已售罄   2是 已下架
      NotifyManager.showToast('该商品已售罄~');
      isGrounding = false;
    } else if (status == 2) {
      //0是正常的  1是已售罄   2是 已下架
      NotifyManager.showToast('该商品已下架~');
      isGrounding = false;
    }
  }
  return isGrounding;
}

DateTime getDataTime(String time) {
  int year = int.parse(time.split(" ")[0].split('-')[0]);
  int month = int.parse(time.split(" ")[0].split('-')[1]);
  int day = int.parse(time.split(" ")[0].split("-")[2]);
  int hour = int.parse(time.split(" ")[1].split(':')[0]);
  int min = int.parse(time.split(" ")[1].split(':')[1]);
  String secs = time.split(" ")[1].split(':')[2];
  if (secs.contains(".")) {
    secs = secs.split(".")[0];
  }
  int sec = int.parse(secs);
  DateTime date = new DateTime(year, month, day, hour, min, sec);
  return date;
}

///根据 文字宽度算文字的长度 ，间接计算出 行数
int paintWidthWithTextStyle(TextStyle style, String text, double textWidth) {
  final TextPainter textPainter = TextPainter(
      text: TextSpan(text: text, style: style),
      maxLines: 1,
      textDirection: TextDirection.ltr)
    ..layout(minWidth: 0, maxWidth: double.infinity);
  double width = textPainter.size.width;
  int lineNum = (width * 1.00) ~/ (textWidth * 1.00);
  double lineNumD = (width * 1.00) / (textWidth * 1.00);
//    TblLogUtil.d("gxj=line="+lineNumD.toString());
  if (lineNumD - lineNum >= 0.99) {
    lineNum = lineNum + 2;
  } else {
    lineNum = lineNum + 1;
  }
  return lineNum;
}
